package com.niit.gams.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.niit.gams.dao.SysResourceMapper;
import com.niit.gams.pojo.SysResource;
import com.niit.gams.service.SysResourceService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysResourceServiceImpl implements SysResourceService {
  private SysResourceMapper resourceMapper;

  public SysResourceServiceImpl(SysResourceMapper resourceMapper) {
    this.resourceMapper = resourceMapper;
  }

  @Override
  public List<SysResource> findResourcesInRoleId(List<Long> rids) {
    return resourceMapper.findResourcesInRoleId(rids);
  }

  @Override
  public PageInfo<SysResource> findResourcesByPage(Integer curPage, Integer pageSize) {
    PageHelper.startPage(curPage,pageSize);
    List<SysResource> resources = resourceMapper.findResourcesByPage(curPage, pageSize);
    PageInfo<SysResource> pageInfo = new PageInfo<>(resources);
    return pageInfo;
  }

  @Override
  public boolean addPriv(SysResource resource) {
    boolean flag = resourceMapper.insert(resource)>0;
    return flag;
  }

  @Override
  public boolean delPriv(Integer pid) {
    boolean flag = resourceMapper.deleteByPrimaryKey(pid)>0;
    return flag;
  }

  @Override
  public List<SysResource> findAll() {
    return resourceMapper.selectAll();
  }

  @Override
  public List<Long> findPrivs(Long rid) {
    List<Long> rids = new ArrayList<>();
    rids.add(rid);
    List<SysResource> resources = findResourcesInRoleId(rids);
    List<Long> pids = new ArrayList<>();
    for (SysResource resource:resources) {
       pids.add(resource.getId());
    }
    return pids;
  }

  @Override
  public boolean updateRolePrivs(Long rid, List<Long> pids) {

    //先删除rid角色的所有关联权限
    boolean flag = resourceMapper.deletePidsByRid(rid)>0;
    //重新添加rid角色的关联权限

    boolean  rFlag = resourceMapper.insertPidsByRid(rid,pids)>0;

    return rFlag;
  }
}
